﻿using ICSharpCode.AvalonEdit;
using Oxage.Common;
using Oxage.Models;
using Oxage.Views;

namespace Oxage.Services
{
	public class DialogService
	{
		public static FindWindowCallback GetFindWindowCallback(TextEditor editor)
		{
			var findCallback = new FindWindowCallback((action, result) =>
			{
				switch (action)
				{
					case FindWindowAction.Find:
						int index = editor.Text.IndexOf(result.FindText, editor.TextArea.Caret.Offset);
						if (index >= 0)
						{
							editor.Select(index, result.FindText.Length);
							editor.CaretOffset = index;
						}
						else
						{
							//TODO: Start from beginning?
						}
						break;

					case FindWindowAction.Replace:
						break;
				}
			});

			return findCallback;
		}

		public static void Find()
		{
			var editor = TextEditorService.ActiveTextEditor;
			if (editor == null)
			{
				return;
			}

			var findCallback = GetFindWindowCallback(editor);
			FindWindow.ShowFindDialog(editor.SelectedText, findCallback);
		}

		public static void FindNext()
		{
			if (FindWindow.LastDialog != null)
			{
				FindWindow.LastDialog.FindNext();
			}
			else
			{
				Find();
			}
		}

		public static void Replace()
		{
			var editor = TextEditorService.ActiveTextEditor;
			if (editor == null)
			{
				return;
			}

			var findCallback = GetFindWindowCallback(editor);
			FindWindow.ShowReplaceDialog(editor.SelectedText, "", findCallback);
		}

		public static void JumpToLine()
		{
			var editor = TextEditorService.ActiveTextEditor;
			if (editor == null)
			{
				return;
			}

			JumpToLineWindow.ShowDialog(editor.TextArea.Caret.Line, editor.LineCount, line =>
			{
				editor.TextArea.Caret.Line = line;
				editor.ScrollToLine(line);
			});
		}

		public static void ShowApplicationSettings()
		{
			//new OptionsWindow().Show();

			//So far when GUI is not finished and settings change rapidly the application configuration is changed in a file
			var runner = new NotepadRunner();
			runner.Run("program.ini");
		}

		public static void ShowMachineSettings()
		{
			//So far when GUI is not finished and settings change rapidly the machine configuration is changed directly in a file
			var runner = new NotepadRunner();
			runner.Run("machine.ini");

			//MachineService.TrackConfigurationFile();
			//MachineService.LoadConfig("machine.ini");
		}

		public static void ShowHelp()
		{
			//TODO: Show html help page in web browser
		}

		public static void ShowAbout()
		{
			//TODO: Reuse window
			new AboutWindow().Show();
		}
	}
}
